package day31;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @author: 王丹
 * @create: 2021-08-03 21:53
 * 方式6：CompletableFuture方式实现:等待线程完成
 **/
public class Demo06 {
    /**
     * CompletableFuture.supplyAsync可以用来异步执行一个带返回值的任务，调用completableFuture.get()
     * 会阻塞当前线程，直到任务执行完毕，get方法才会返回。
     */
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println(System.currentTimeMillis());
        CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 10;
        });
        System.out.println(System.currentTimeMillis());
        //futureTask.get()会阻塞当前线程，直到futureTask执行完毕
        Integer result = completableFuture.get();
        System.out.println(System.currentTimeMillis() + ":" + result);

    }
}
